package com.ramos.kuaixiao.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.TextView;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.adapter.CustomerAdapter;
import com.ramos.kuaixiao.db.CustomerDB;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.Utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

public class CustomerActivity extends BaseActivity implements OnClickListener{
    private static String TAG = "CustomerActivity";
    private Context mContext;
    private LinearLayout ll_unfinished_none;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;
    public final static int REFRESH_SUCCESS = 200;
    public final static int UPLOAD_ALL_SUCCESS = 300;
    public final static int UPLOAD_ALL_FAIL = 301;
    private CustomerAdapter mAdapter;
    private List<Customer> productList = new ArrayList<>();
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLinearLayoutManager;
    SearchView searchview;
    GeocodeSearch geocoderSearch;
    CustomerDB db;
    private boolean mIsFilter = false;
    private List<Customer> mTmpList = new ArrayList<>();
    private List<Customer> mFilterList = new ArrayList<>();
    private String mFilterWord;
    LinearLayout title_reback;

    @Override
    public void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        setContentView(R.layout.activity_customer);
        mContext = this;
        initView();
    }

    private void initView() {
        db = new CustomerDB();
        title_reback = findViewById(R.id.title_reback);
        title_reback.setVisibility(View.VISIBLE);
        title_reback.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        searchview = findViewById(R.id.shop_Searchview);
        int id = searchview.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
        TextView textView = searchview.findViewById(id);
        textView.setTextSize(16);//字体、提示字体大小
        searchview.setQueryHint("搜索商店(至少输入两个字)");
        searchview.setIconified(false);
        searchview.setIconifiedByDefault(false);
        int magId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
        ImageView magImage = searchview.findViewById(magId);
        magImage.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
        Class<?> c = searchview.getClass();
        try {
            Field f = c.getDeclaredField("mSearchPlate");//通过反射，获得类对象的一个属性对象
            f.setAccessible(true);//设置此私有属性是可访问的
            View v = (View) f.get(searchview);//获得属性的值
            v.setBackgroundColor(Color.TRANSPARENT);//设置此view的背景
        } catch (Exception e) {
            e.printStackTrace();
        }

        ll_unfinished_none = findViewById(R.id.ll_unfinished_none);

        mRecyclerView = findViewById(R.id.list_task);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mAdapter = new CustomerAdapter(mContext, productList);
        mAdapter.setUpdateCarListener(new UpdateListener());
        mRecyclerView.setAdapter(mAdapter);
        searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String arg0) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean onQueryTextChange(String queryText) {
                mFilterWord = queryText;
                if (StringUtil.isEmpty(queryText)) {
                    if (mTmpList.size() > 0) {
                        mRecyclerView.setVisibility(View.VISIBLE);
                        ll_unfinished_none.setVisibility(View.GONE);
                        mAdapter.refresh(mTmpList);
                    }
                    mIsFilter = false;
                } else if (queryText.length() >= 2) {
                    mAdapter.getFilter().filter(queryText);
                }
                return true;
            }
        });
    }

    @Override
    public void onClick(View v) {

    }

    class UpdateListener implements CustomerAdapter.UpdateCarListener {
        @Override
        public void update(int num, List<Customer> tasklist) {
            if (tasklist == null || tasklist.size() == 0) {
                if (!StringUtil.isEmpty(mFilterWord)) {
                    mRecyclerView.setVisibility(View.GONE);
                    ll_unfinished_none.setVisibility(View.VISIBLE);
                }
            } else {
                mFilterList.clear();
                mFilterList.addAll(tasklist);
                mRecyclerView.setVisibility(View.VISIBLE);
                ll_unfinished_none.setVisibility(View.GONE);
                //mPageFilterList = getPageList(mFilterList);
                mAdapter.refresh(mFilterList);
                mIsFilter = true;
                Product product = new Product(mFilterList);
                product.executeOnExecutor(Executors.newCachedThreadPool());
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        searchview.clearFocus();
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH_SUCCESS:
                    List<Customer> productList = (List<Customer>) msg.obj;
                    mAdapter.refresh(productList);
                    if (!mIsFilter) {
                        mTmpList.clear();
                        mTmpList.addAll(productList);
                    }
                    searchview.clearFocus();
                    break;

                case UPLOAD_ALL_SUCCESS:
                    break;
                case UPLOAD_ALL_FAIL:
                    mRecyclerView.setVisibility(View.GONE);
                    ll_unfinished_none.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
        }
    };


    class Product extends AsyncTask<String, String, String> {
        private List<Customer> productList = new ArrayList<>();

        public Product(List<Customer> type) {
            productList = type;
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                for (int i = 0; i < productList.size(); i++) {
                    final Customer customer = productList.get(i);
                    Log.d("onGeocodeSearched", "" + customer.getAddress() + " : " + customer.getCity());
                    if (!StringUtil.isEmpty(customer.getAddress()) && !StringUtil.isEmpty(customer.getCity())) {
                        geocoderSearch = new GeocodeSearch(mContext);
                        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                            @Override
                            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                            }

                            @Override
                            public void onGeocodeSearched(GeocodeResult result, int rCode) {
                                if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                                    if (result != null && result.getGeocodeAddressList() != null
                                            && result.getGeocodeAddressList().size() > 0) {
                                        GeocodeAddress address = result.getGeocodeAddressList().get(0);
                                        LatLonPoint latLonPoint = address.getLatLonPoint();
                                        //Log.d("onGeocodeSearched", latLonPoint.toString() + " " );
                                        if (latLonPoint != null && !StringUtil.isEmpty(SharedPreference.getPreferString("latitude"))
                                                && !StringUtil.isEmpty(SharedPreference.getPreferString("longitude"))) {
                                            double dis = Utils.getDistance(latLonPoint.getLatitude(), latLonPoint.getLongitude(), Double.valueOf(SharedPreference.getPreferString("latitude")),
                                                    Double.valueOf(SharedPreference.getPreferString("longitude")));
                                            customer.setDistance(String.valueOf(App.df1.format(dis)) + "");
                                            //mAdapter.refresh(productList);
                                            sendMessagea(REFRESH_SUCCESS, productList);
                                        }
                                    }
                                }
                            }
                        });
                        GeocodeQuery query = new GeocodeQuery(customer.getAddress(), customer.getCity());// 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode，
                        geocoderSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求
                    }
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            Log.d("onGeocodeSearched", "" + productList.size());
            //mAdapter.refresh(productList);
        }
    }

    private void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }

}
